<template>
  <a-modal v-model:open="open" v-model:title="title" @ok="handleOk" @cancel="handleCancle" width="470px">
    <div>
      <a-form ref="formPwdRef" :model="formPwd" :rules="rules" :label-col="{ style: 'width:104px' }">
        <a-form-item label="原密码" name="orgPwd">
          <a-input-password v-model:value="formPwd.orgPwd" placeholder="请输入" style="width: 342px; height: 32px"
            :maxlength="32" />
        </a-form-item>
        <a-form-item label="新密码" name="newPwd" class="newPwd-style">
          <a-input-password v-model:value="formPwd.newPwd" placeholder="请输入" style="width: 342px; height: 32px"
            :maxlength="32" />
        </a-form-item>

        <p v-if="showPasswordRule" class="pwd-rules" :style="{ color: isPasswordValid ? '#00000040' : '#ff4d4f' }">
          密码最小长度为8，必须至少包含一个大写字母、一个小写字母、一个特殊字符、数字、不可包含账号
        </p>
        <p v-else class="pwd-empty">此项不能为空</p>

        <a-form-item label="确认密码" name="confPwd">
          <a-input-password v-model:value="formPwd.confPwd" placeholder="请输入" style="width: 342px; height: 32px"
            :maxlength="32" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>
<script setup>
import { reactive, ref, watch } from 'vue'
import { useVModel } from '@vueuse/core'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { userLogout } from '@/api/account'
import { useAccountStore } from '@/stores/account'
import { storeToRefs } from 'pinia'
import { resetPassword, changePassword, validateOldPassword } from '@/api/pw.js'
import CryptoJS from 'crypto-js'

let router = useRouter()
let accountStore = useAccountStore()
let account = storeToRefs(accountStore)
/**
 * 外部参数
 */
let props = defineProps({
  open: { type: Boolean, default: () => true },
  title: {
    type: String,
    default() {
      return ''
    },
  },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:open', 'update:title'])
/**
 * 双向绑定
 */
let open = useVModel(props, 'open', emit)
let title = useVModel(props, 'title', emit)

let formPwdRef = ref()
const isPasswordValid = ref(true)
const showPasswordRule = ref(true)
let workNumber = ref(account.username.value)
const passwordRegex =
  /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])[A-Za-z\d!@#$%^&*(),.?":{}|<>]{8,32}$/
let formPwd = reactive({
  orgPwd: undefined,
  newPwd: undefined,
  confPwd: undefined,
})
let rules = {
  orgPwd: [
    {
      required: true,
      validator: validateorgPwd,
      trigger: 'blur',
    },
  ],
  newPwd: [
    {
      required: true,
      validator: validateNewPassword,
      trigger: 'change',
    },
  ],
  confPwd: [
    {
      required: true,
      validator: validateConfPassword,
      trigger: 'change',
    },
  ],
}
let aseKey = '123456'
// ecb信息加密
const encryptInfo = info => {
  let newinfo = CryptoJS.AES.encrypt(
    CryptoJS.enc.Utf8.parse(info),
    CryptoJS.enc.Utf8.parse(aseKey),
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    },
  ).toString() // 用户密码加密
  return newinfo
}
function handleOk() {
  if (open.value) {
    formPwdRef.value
      .validate()
      .then(() => {
        let oldParams = {
          userId: account.userid.value,
          oldPassword: encryptInfo(formPwd.orgPwd),
        }

        let params = {
          userId: account.userid.value,
          newPassword: encryptInfo(formPwd.newPwd),
        }
        open.value = false
        formPwdRef.value.resetFields()
        changePassword(params)
          .then(async res => {
            if (res.success) {
              message.success('密码修改成功')
              await userLogout()
              accountStore.logout()
              router.push('/sign/login')
            }
          })
          .catch(() => {
            message.error('密码修改失败')
          })
      })
      .catch(() => {
        message.error('密码修改失败')
      })
  }
}

let handleCancle = () => {
  open.value = false
  isPasswordValid.value = true
  showPasswordRule.value = true
  formPwdRef.value.resetFields()
}

/*校验原始密码*/
async function validateorgPwd(rule, value) {
  if (!value) {
    return Promise.reject('此项不能为空')
  } else {
    let params = {
      userId: account.userid.value,
      oldPassword: encryptInfo(formPwd.orgPwd),
    }
    let result = await validateOldPassword(params)
    if (!result.data) {
      return Promise.reject('原密码输入错误')
    } else {
      return Promise.resolve()
    }
  }
}
/* 校验新密码*/
function validateNewPassword(rule, value) {
  if (!value) {
    showPasswordRule.value = false
    return Promise.reject()
  } else {
    if (!passwordRegex.test(value) || value.includes(workNumber.value)) {
      showPasswordRule.value = true
      isPasswordValid.value = false
      return Promise.reject()
    } else if (formPwd.confPwd) {
      formPwdRef.value.validateFields(['confPwd'])
    } else {
      showPasswordRule.value = true
      isPasswordValid.value = true
      return Promise.resolve()
    }
  }
  return Promise.resolve()
}
/* 校验确认密码*/
function validateConfPassword(rule, value) {
  if (!value) {
    return Promise.reject(new Error('此项不能为空'))
  }
  if (!passwordRegex.test(value)) {
    return Promise.reject(new Error('格式错误'))
  }
  if (value.includes(account.username.value)) {
    return Promise.reject(new Error('格式错误'))
  }
  if (value !== formPwd.newPwd && formPwd.newPwd) {
    return Promise.reject(new Error('与新密码不一致'))
  }
  return Promise.resolve()
}
</script>
<style lang="less" scoped>
:global(.ant-modal .ant-modal-content) {
  padding: 16px 0px 10px 0px;
  background: #fff;
  border-radius: 2px;
  box-shadow:
    0 6px 16px 0 rgba(0, 0, 0, 0.08),
    0 9px 4px 0 rgba(0, 0, 0, 0.05),
    0 12px 48px 16px rgba(0, 0, 0, 0.03);
}

:global(.ant-modal .ant-modal-footer) {
  padding-right: 24px;
  padding-top: 10px;
  border-top: 1px solid rgba(0, 0, 0, 0.09);
}

:global(.ant-modal .ant-modal-header .ant-modal-title) {
  line-height: 24px;
  font-weight: 500;
  font-family: PingFangSC-Medium;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 16px;
}

:global(.ant-modal .ant-modal-header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.09);
  padding-left: 24px;
  margin-bottom: 24px;
}

:global(.ant-form-item .ant-form-item-label) {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
  line-height: 22px;
  text-align: right;
  font-family: PingFangSC-Regular;
}

.pwd-rules {
  margin: 0px 0px 24px 116px;
  width: 330px;
  height: 44px;
  font-size: 14px;
  line-height: 22px;
}

.pwd-empty {
  margin: 0px 0px 0px 106px;
  width: 330px;
  height: 22px;
  font-size: 14px;
  line-height: 22px;
  color: #ff4d4f;
}

:global(.ant-form-item-explain-error) {
  height: 0px;
}

.newPwd-style {
  margin-bottom: 0px;
}
</style>
